import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/gestures.dart';
import 'dart:async';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();
  bool _isAgreed = false;
  int _countDown = 0;
  Timer? _timer;

  // 验证手机号格式
  bool _isValidPhone(String phone) {
    RegExp regex = RegExp(r'^1[3-9]\d{9}$');
    return regex.hasMatch(phone);
  }

  // 开始倒计时
  void _startCountDown() {
    if (_countDown == 0 && _isValidPhone(_phoneController.text)) {
      setState(() {
        _countDown = 60;
      });
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        setState(() {
          if (_countDown > 0) {
            _countDown--;
          } else {
            _timer?.cancel();
          }
        });
      });
      // TODO: 在这里添加发送验证码的逻辑
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    _phoneController.dispose();
    _codeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const SizedBox(height: 40),
            // 手机号输入框
            TextField(
              controller: _phoneController,
              keyboardType: TextInputType.phone,
              maxLength: 11,
              decoration: const InputDecoration(
                labelText: '手机号',
                hintText: '请输入手机号',
                prefixIcon: Icon(Icons.phone),
                border: OutlineInputBorder(),
              ),
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
              ],
            ),
            const SizedBox(height: 16),
            // 验证码输入框和发送按钮
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _codeController,
                    keyboardType: TextInputType.number,
                    maxLength: 4,
                    decoration: const InputDecoration(
                      labelText: '验证码',
                      hintText: '请输入验证码',
                      prefixIcon: Icon(Icons.lock),
                      border: OutlineInputBorder(),
                    ),
                    inputFormatters: [
                      FilteringTextInputFormatter.digitsOnly,
                    ],
                  ),
                ),
                const SizedBox(width: 16),
                SizedBox(
                  width: 120,
                  child: ElevatedButton(
                    onPressed: _countDown > 0 ? null : _startCountDown,
                    child: Text(_countDown > 0 ? '${_countDown}s' : '发送验证码'),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 24),
            // 用户协议
            Row(
              children: [
                Checkbox(
                  value: _isAgreed,
                  onChanged: (value) {
                    setState(() {
                      _isAgreed = value ?? false;
                    });
                  },
                ),
                Expanded(
                  child: Text.rich(
                    TextSpan(
                      text: '我已阅读并同意',
                      children: [
                        TextSpan(
                          text: '《用户协议》',
                          style: const TextStyle(color: Colors.blue),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              // TODO: 打开用户协议
                            },
                        ),
                        const TextSpan(text: '和'),
                        TextSpan(
                          text: '《隐私政策》',
                          style: const TextStyle(color: Colors.blue),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              // TODO: 打开隐私政策
                            },
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 24),
            // 登录按钮
            ElevatedButton(
              onPressed: (!_isAgreed ||
                      _phoneController.text.isEmpty ||
                      _codeController.text.length != 4)
                  ? null
                  : () {
                      if (!_isValidPhone(_phoneController.text)) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('请输入正确的手机号')),
                        );
                        return;
                      }
                      // TODO: 在这里添加登录逻辑
                    },
              child: const Padding(
                padding: EdgeInsets.all(12.0),
                child: Text('登录'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
